<template>
  <div>
    <el-dialog title="登录账号" v-model="dialogVisible" width="500px" :before-close="handleClose">
      <div style="padding: 40px">
        <el-form :model="loginForm" :rules="loginRules" ref="refForm" label-width="80px">
          <el-form-item label="账号" prop="account">
            <el-input v-model="loginForm.account" placeholder="输入你的账号" clearable></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="loginForm.password" placeholder="输入你的密码" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model="loginForm.code" style="max-width: 600px" placeholder="输入验证码">
              <template #suffix>
                <el-image @click="refreshCaptcha" style="width: 80px; height: 30px" :src="`data:image/png;base64,${loginForm.captcha}`" fit="cover" />
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" style="text-align: center; padding: 10px 0px 50px 0px">
        <el-button type="primary" @click="handleSubmit()" :loading="loading">
          {{ loading ? 'Submitting ...' : '登录账号' }}
        </el-button>
        <el-button :loading="loading" @click="handleClose(() => {})"> 关闭 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getcaptcha } from '@/apis/auth'
import { sm2 } from 'sm-crypto-v2'

const loading = ref(false)
const dialogVisible = ref(true)

const userStore = useUserStore()

const { loginAccount } = userStore

const loginForm = ref({
  account: import.meta.env.VITE_DEFAULT_ACCOUNT || '',
  password: import.meta.env.VITE_DEFAULT_PASSWORD || '',
  codeId: '',
  code: '',
  captcha: ''
})
// console.log(loginForm)
const loginRules = {
  account: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
}
const refreshCaptcha = () => {
  getcaptcha()
    .then((response) => {
      let { code, message, result } = response.data
      if (code !== 200) {
        throw new Error(message || '获取验证码失败')
      }
      loginForm.value.codeId = result.id
      loginForm.value.captcha = result.img
      // console.log('验证码获取成功:', loginForm.value)
    })
    .catch((error) => {
      console.error('验证码获取失败:', error)
    })
}

onMounted(() => {
  refreshCaptcha()
})
const refForm = ref<FormInstance>()

const handleSubmit = () => {
  refForm.value?.validate((valid: boolean) => {
    if (!valid) {
      console.log('error submit!!')
      return
    }

    loading.value = true

    // SM2加密密码
    // const keys = SM2.generateKeyPair();
    const publicKey = `0484C7466D950E120E5ECE5DD85D0C90EAA85081A3A2BD7C57AE6DC822EFCCBD66620C67B0103FC8DD280E36C3B282977B722AAEC3C56518EDCEBAFB72C5A05312`
    const password = sm2.doEncrypt(loginForm.value.password, publicKey, 1)

    let data = {
      account: loginForm.value.account,
      password: password,
      codeId: loginForm.value.codeId,
      code: loginForm.value.code
    }
    loginAccount(data)
      .then((response: any) => {
        let { code, message, result } = response.data
        if (code !== 200) {
          refreshCaptcha()
          ElMessage.info(message || '登录失败')
          return
        }
        ElMessage.success('登录成功')
        dialogVisible.value = false
      })
      .catch((error) => {
        ElMessage.error('登录失败，请检查账号密码或验证码是否正确')
        console.error('登录失败:', error)
      })
      .finally(() => {
        loading.value = false
        refForm.value?.resetFields()
      })
  })
}

const handleClose = (done: () => void) => {
  if (done) {
    done()
  }
  dialogVisible.value = false
  loading.value = false
}
const handleShow = () => {
  dialogVisible.value = true
  loading.value = false
}

defineExpose({
  handleShow
})
</script>

<style></style>
